interface waitTimer {
    key: string,
    time: number,
    timeout: number,
    executionMethod: Function,
    timeoutMethod: Function,
    currentTimeout: number,
    timer: number
}

let _waitData: waitTimer[] = [];

export const clearAllInterval = () => {
    for (let i = 0; i < _waitData.length; i++) {
        clearInterval(_waitData[i].timer);
    }
    _waitData = [];
}

/**
 * 设置等待循环执行的方法
 * @param key key
 * @param time 循环时间
 * @param timeout 超时次数
 * @param executionMethod 执行的方法
 * @param timeoutMethod 超时事件
 */
export const setWaitInterval = (
    key: string,
    time: number,
    timeout: number,
    executionMethod: (key: string) => void,
    timeoutMethod: (key: string) => void,
) => {
    //如果有相同先删除
    removeWaitInterval(key);
    const timer = setInterval(
        (key1: string) => {
            if (!waitExecutionFunction(key1)) {
                executionMethod(key1);
            }
        },
        time,
        key,
    );
    let data = {
        key: key,
        time: time,
        timeout: timeout,
        executionMethod: executionMethod,
        timeoutMethod: timeoutMethod,
        currentTimeout: 0,
        timer: timer,
    };
    _waitData.push(data);
};
/**
 * 删除定时执行
 * @param key key
 */
export const removeWaitInterval = (key: string): boolean => {
    let target = getClock(key);
    if (target == null) {
        return false;
    }
    clearInterval(target.timer);
    _waitData.splice(_waitData.indexOf(target), 1);
    return true;
};
//等待执行的方法
const waitExecutionFunction = (key: string): boolean => {
    let target = getClock(key);
    if (target == null) {
        return true;
    }
    target.currentTimeout = target.currentTimeout + 1;
    if (target.currentTimeout > target.timeout) {
        target.timeoutMethod(key);
        clearInterval(target.timer);
        return true;
    }
    return false;
};
function getClock(key: string) {
    let target = _waitData.find(function (item) {
        return item.key === key;
    })
    if (target) {
        return target;
    }
    return null;
}

